<template>
  <div>
    <div style="margin: 10px 0">
      <el-input
        style="width: 200px"
        placeholder="请输入充电宝名称"
        suffix-icon="el-icon-search"
        v-model="name"
      ></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd"
        >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>
      <el-popconfirm
        class="ml-5"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
      >
        <el-button type="danger" slot="reference"
          >批量删除 <i class="el-icon-remove-outline"></i
        ></el-button>
      </el-popconfirm>
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      :header-cell-class-name="'headerBg'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="siteName" label="站点名称"></el-table-column>
      <el-table-column prop="name" label="充电宝名称"></el-table-column>
      <el-table-column prop="brand" label="充电宝品牌"></el-table-column>
      <el-table-column prop="img" label="图片">
        <template class="block" v-slot:default="scope">
          <el-popover placement="left" trigger="click" width="300">
            <img :src="scope.row.img" width="100%" />
            <img
              slot="reference"
              :src="scope.row.img"
              :alt="scope.row.img"
              style="max-height: 70px; max-width: 70px; padding: 5px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="审核">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            active-color="#13ce66"
            inactive-color="#ccc"
            @change="changeEnable(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="useTime" label="使用时间(天)"></el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)"
            >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
            class="ml-5"
            confirm-button-text="确定"
            cancel-button-text="我再想想"
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference"
              >删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog title="充电宝信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="90px" size="small">
        <el-form-item label="站点">
          <el-select v-model="selectValue" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :value="item.siteName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电宝名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="充电宝品牌">
          <el-input v-model="form.brand" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            v-model="form.img"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="handlerChange"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PowerBank",
  data() {
    return {
      form: {},
      tableData: [],
      name: "",
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      teachers: [],
      user: localStorage.getItem("user")
        ? JSON.parse(localStorage.getItem("user"))
        : {},
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      dialogImageUrl: "",
      dialogVisible: false,
      userId: "",
      role: "",
      selectValue: "",
      options: {},
      primaryKey: "",
      img: "",
    };
  },
  created() {
    this.load();
  },
  methods: {
    //图片上传成功
    handleAvatarSuccess(res, file) {
      this.img = res;
      this.form.img = res;
    },
    //上传站点图片
    handlerChange(param) {
      let formData = new FormData();
      formData.append("file", param.file);
      formData.append("id", this.primaryKey);
      this.request.post("/site/upload", formData).then((res) => {
        this.img = res;
        this.form.img = this.img;
      });
    },
    //上传图片前进行校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isJPG && isLt2M;
    },
    load() {
      this.request
        .get("/powerBank/getAll", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            userId: this.user.id,
            role: this.user.role,
            name: this.name,
          },
        })
        .then((res) => {
          this.tableData = res.records;
          console.log(res);
          this.total = res.total;
        });
    },
    changeEnable(row) {
      console.log(row);
      this.request.post("/powerBank/saveOrUpdate", row).then((res) => {
        console.log(res);
        if (res.code === "200") {
          this.$message.success("操作成功");
          console.log(res);
        }
      });
    },
    handleAdd() {
      this.form = {};
      this.dialogFormVisible = true;
      this.request
        .get("/site/getList", {
          params: {
            pageNum: 0,
            pageSize: 400,
            userId: this.user.id,
            role: this.user.role,
          },
        })
        .then((res) => {
          this.options = res.records;
        });
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.request
        .get("/site/getList", {
          params: {
            pageNum: 0,
            pageSize: 400,
            userId: this.user.id,
            role: this.user.role,
          },
        })
        .then((res) => {
          this.options = res.records;
        });
      this.primaryKey = this.form.id;
      this.dialogFormVisible = true;
    },
    del(id) {
      this.request.post("powerBank/delete/" + id).then((res) => {
        if (res.code === "200") {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delBatch() {
      let ids = this.multipleSelection.map((v) => v.id); // [{}, {}, {}] => [1,2,3]
      console.log(ids);
      this.request.post("/powerBank/del/batch", ids).then((res) => {
        if (res.code === "200") {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      });
    },
    save() {
      this.form.userId = this.user.id;
      // 保存站点信息
      if (this.options != null && this.selectValue != null) {
        for (var i = 0; i < this.options.length; i++) {
          if (this.options[i].siteName == this.selectValue) {
            this.form.siteId = this.options[i].id;
          }
        }
      }
      // 发送新增或修改请求
      this.request.post("/powerBank/saveOrUpdate", this.form).then((res) => {
        if (res.code === "200") {
          this.$message.success("保存成功");
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("保存失败");
        }
      });
    },
    reset() {
      this.name = "";
      this.load();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
    download(url) {
      window.open(url);
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
